﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Common;
using log4net;
using SqlSugar;
using AutoFacUtils;
using CashFlow.Web.Def;
using CashFlow.Db.DAL;
using CashFlow.Db.Entity;
using CashFlow.Db.Repository;
using CashFlow.Web.Service;
using System.Diagnostics;
using CashFlow.Web.Common;
using CashFlow.Web.Models.Order.Result;

namespace CashFlow.Web.Service.Implement
{
    public class OrderService : MyService<OrderEntity>, IOrderService
    {
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }
        private IShopUserService GetShopUserService() { return AutoFacHelper.Get<IShopUserService>(); }

        public IList<OrderBuySellInfoModel> QueryAllOrders2(string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<OrderEntity>()
                           .InnerJoin<UserInfoEntity>((o, u) => o.BuyerUserId == u.Id)
                           .InnerJoin<UserInfoEntity>((o, u, u2) => o.SellerUserId == u2.Id)
                           .Where((o, u, u2) => o.CreateTime.ToString("yyyy-MM-dd") == date)
                           .Select((o, u, u2) => new OrderBuySellInfoModel
                           {
                               OrderId = o.Id,
                               OrderNo = o.OrderNo,
                               Amount = o.Amount,
                               State = o.State,
                               Buyer = u.Name,
                               Seller = u2.Name
                           })
                           .ToList();
                return ls;
            }
        }

        public IList<OrderAndUserInfo> QueryAllChildUsersOrder(
            int userId
            , string date
            , int? userState)
        {
            var service = GetUserService();
            var users = service.QueryAllChildUsersByUserId(userId, userState);
            var userIds = users.Select(x => x.Id).ToList();
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<OrderEntity>()
                           .InnerJoin<UserInfoEntity>((o, u) => o.BuyerUserId == u.Id)
                           .Where((o, u) => o.CreateTime.ToString("yyyy-MM-dd") == date
                                && userIds.Contains(u.Id))
                           .Select((o, u) => new OrderAndUserInfo
                           {
                               OrderInfo = o,
                               UserInfo = u
                           })
                           .ToList();
                return ls;
            }
        }

        public IList<OrderBuySellInfoModel> QueryShopAllChildUsersOrder(
            int userId
            , string date
            , int? visible
            , int? userState)
        {
            var service = GetUserService();
            var users = service.QueryShopUsersByUserId(
                            userId
                            , userState
                        );
            var userIds = users.Select(x => x.Id).ToList();
            using (var db = SqlSugarHelper.GetDb())
            {
                var query = db.Queryable<OrderEntity>()
                              .InnerJoin<UserInfoEntity>((o, u) => o.BuyerUserId == u.Id)
                              .InnerJoin<UserInfoEntity>((o, u, u2) => o.SellerUserId == u2.Id)
                              .Where((o, u, u2) => o.CreateTime.ToString("yyyy-MM-dd") == date
                                    && userIds.Contains(u.Id));

                if (visible.HasValue)
                {
                    query = query.Where((o, u, u2) => o.Visible == visible.Value);
                }
                if (userState.HasValue)
                {
                    query = query.Where((o, u, u2) => o.State == userState.Value);
                }

                var ls = query.Select((o, u, u2) => new OrderBuySellInfoModel
                {
                    OrderId = o.Id,
                    OrderNo = o.OrderNo,
                    Amount = o.Amount,
                    State = o.State,
                    Buyer = u.Name,
                    Seller = u2.Name
                }).ToList();

                return ls;
            }
        }

        public int QueryShopAllChildUsersOrderCount(
            int userId
            , string date
            , int? visible
            , int? userState)
        {
            var service = GetUserService();
            var users = service.QueryShopUsersByUserId(
                            userId
                            , userState
                        );
            var userIds = users.Select(x => x.Id).ToList();
            using (var db = SqlSugarHelper.GetDb())
            {
                var query = db.Queryable<OrderEntity>()
                              .InnerJoin<UserInfoEntity>((o, u) => o.BuyerUserId == u.Id)
                              .InnerJoin<UserInfoEntity>((o, u, u2) => o.SellerUserId == u2.Id)
                              .Where((o, u, u2) => o.CreateTime.ToString("yyyy-MM-dd") == date
                                    && userIds.Contains(u.Id));

                if (visible.HasValue)
                {
                    query = query.Where((o, u, u2) => o.Visible == visible);
                }
                if (userState.HasValue)
                {
                    query = query.Where((o, u, u2) => o.State == userState.Value);
                }

                var count = query.Count();

                return count;
            }
        }

        public IList<OrderBuySellInfo> QueryOrders(
            int userId
            , string date
            , int visibile)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<OrderEntity>()
                    .InnerJoin<UserInfoEntity>((o, u1) => o.BuyerUserId == u1.Id)
                    .InnerJoin<UserInfoEntity>((o, u1, u2) => o.SellerUserId == u2.Id)
                    .Where((o, u1, u2) => o.CreateTime.ToString().Substring(0, 10) == date
                        && (u1.Id == userId || u2.Id == userId)
                        && o.Visible == visibile)
                    .Select((o, u1, u2) => new OrderBuySellInfo
                    {
                        Order = o,
                        Buyer = u1,
                        Seller = u2
                    })
                    .ToList();

                return ls;
            }
        }

        public IList<OrderEntity> QueryAllOrders(string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<OrderEntity>()
                           .Where(x => x.CreateTime.ToString("yyyy-MM-dd") == date)
                           .ToList();
                return ls;
            }
        }

        public bool IsLegalBuySellInfo(
            string date
            , int orderId
            , int buyerUserId
            , int sellerUserId)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<OrderEntity>()
                          .Where(x => x.CreateTime.ToString("yyyy-MM-dd") == date
                            && x.Id == orderId
                            && x.BuyerUserId == buyerUserId
                            && x.SellerUserId == sellerUserId)
                          .Count();
                return n > 0;
            }
        }

        public bool UpdateOrderState(int orderId, int state)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var entity = db.Queryable<OrderEntity>().Where(x => x.Id == orderId).First();
                if (entity != null)
                {
                    entity.State = state;
                    int n = db.Updateable(entity).ExecuteCommand();
                    return n > 0;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool UpdateUploadPeymentVoucherImagePath(
            int orderId
            , string path)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var item = db.Queryable<OrderEntity>().Where(x => x.Id == orderId).First();
                if (item != null)
                {
                    item.PaymentVoucherImagePath = path;
                    int n = db.Updateable<OrderEntity>(item).ExecuteCommand();
                    return n > 0;
                }
                return false;
            }
        }

        public bool UpdateUploadPeymentVoucherImagePathAndState(
            int orderId
            , string path
            , int state)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var entity = new OrderEntity();
                entity.Id = orderId;
                db.Tracking(entity);
                entity.State = state;
                entity.PaymentVoucherImagePath = path;
                int n = db.Updateable(entity).ExecuteCommand();
                return n > 0;
            }
        }
    }
}
